from fastapi import APIRouter, HTTPException, status, UploadFile
import string
import random
from fastapi.params import Depends
from utils.alysms import AliyunSMSSender
from schemas.response import  ResultModel,LoginedModel, UpdateModel, UserModel, UpdatedAvatar
from schemas.request import  UpdatePasswordModel, LoginModel,UpdateUsernameModel
from utils.cache import TDDRedis
from services.user import UserServiceClient
from utils.auth import AuthHandler
from utils.alyoss import oss_upload_image
router = APIRouter(prefix="/user")
sms_sender = AliyunSMSSender()
tdd_redis = TDDRedis()
auth_handler = AuthHandler()
user_service_client = UserServiceClient()
@router.get("/smscode/{mobile}", response_model=ResultModel)
async def get_smscode(mobile: str):
    code = "".join(random.sample(string.digits, 4))
    # await sms_sender.send_code(mobile, code)
    await tdd_redis.set_sms_code(mobile, code, 60*5)
    print("短信发送成功" + code)
    return ResultModel()

@router.post("/login", response_model=LoginedModel)
async def login(data: LoginModel):
    mobile = data.mobile
    code = data.code
    cache_code = await tdd_redis.get_sms_code(data.mobile)
    if code != cache_code:
        raise HTTPException(status_code=400, detail="验证码错误")
    user = await user_service_client.get_or_create_mobile(mobile)
    # user, access_token, refresh_token
    tokens = auth_handler.encode_login_token(user.id)
    access_token = tokens['access_token']
    refresh_token = tokens['refresh_token']
    await tdd_redis.set_refresh_token(user.id, refresh_token)
    result = {
        'user':user,
        'access_token': access_token,
        'refresh_token':refresh_token
    }
    return result
@router.get("/access/token")
async def access_token_view(user_id: int=Depends(auth_handler.auth_access_dependency)):
    return {
        "detail": "access_token验证成功",
        "user_id": user_id
    }

@router.get("/refresh/token")
async def refresh_token_view(user_id: int=Depends(auth_handler.auth_refresh_dependency)):
    access_token = auth_handler.encode_update_token(user_id)

    return {
        "detail": "access_token验证成功",
        "access_token": access_token.get('access_token')
    }

@router.post("/logout", response_model=ResultModel)
async def logout(user_id: int=Depends(auth_handler.auth_access_dependency)):
    await tdd_redis.delete_refresh_token(user_id)
    return ResultModel()

@router.put('/update/username', response_model=UpdateModel)
async def update_username(data: UpdateUsernameModel,user_id: int=Depends(auth_handler.auth_access_dependency)):
    username = data.username
    await user_service_client.update_username(user_id=user_id, username=username)
    return UpdateModel()

@router.put("/update/password", response_model=UpdateModel)
async def update_password(data: UpdatePasswordModel, user_id: int=Depends(auth_handler.auth_access_dependency)):
    password = data.password
    await user_service_client.update_password(user_id=user_id, password=password)
    return UpdateModel()

@router.post("/update/avatar", response_model=UpdatedAvatar)
async def update_avatar(
        file: UploadFile,
        user_id: int=Depends(auth_handler.auth_access_dependency)
):
    file_url = await oss_upload_image(file)
    if file_url:
        await user_service_client.update_avatar(user_id=user_id, avatar=file_url)
        return {'file_url': file_url}
    raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail='oss服务到期!头像上传失败')

@router.get('/mine', response_model=UserModel)
async def get_mine_info(user_id: int=Depends(auth_handler.auth_access_dependency)):
    user = user_service_client.get_user_by_id(user_id=user_id)
    return user